<?php namespace App\Observers;

use App\Models\Item;
use App\Models\Match;
use App\Http\Requests\ItemRequest;
use App\Services\MatchService;
use Illuminate\Http\Request;

class ItemObserver
{
    /**
     * 查找可以匹配的物品
     * 先找出确定的分类和地点下的所有物品->对名称、详细地址、描述进行匹配。
     */
    public function created($item)
    {
        $matchService = new MatchService;
        $request = app('request');
        if ($matchItem_id = $request->input('match_id')) {
            return $matchService->create($item->id, $matchItem_id);
        }
        if (Match::where([
                $item->type . '_item_id' => $item->id
            ])->count() == 0 && $matchItem = Item::where([
                'p_catalog_id' => $item->p_catalog_id,
                'catalog_id' => $item->catalog_id,
                'province_id' => $item->province_id,
                'city_id' => $item->city_id,
                'district_id' => $item->district_id,
                'type' => $item->type == 'find' ? 'lost' : 'find',
            ])->first()
        ) {
            return $matchService->create($item->id, $matchItem->id);
        }
    }
}